﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace FS_Unitys.Unitys
{
    public class ToolHelper
    {
        public static string BuildQuery(IDictionary<string, object> parameters, string charset = "utf-8", bool flag = true)
        {
            IEnumerator<KeyValuePair<string, object>> dem = parameters.GetEnumerator();
            return BuildQuery(dem, charset, flag);
        }

        public static string BuildQuery(IEnumerator<KeyValuePair<string, object>> dem, string charset = "utf-8", bool flag = true)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = string.Empty;
                if (dem.Current.Value != null)
                    value = dem.Current.Value.ToString();
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name)) // && !string.IsNullOrEmpty(value)
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }

                    postData.Append(name);
                    postData.Append("=");
                    string encodedValue = string.Empty;
                    if (flag)
                    {
                        encodedValue = HttpUtility.UrlEncode(value, Encoding.GetEncoding(charset));
                    }
                    {
                        encodedValue = value;
                    }

                    postData.Append(encodedValue);
                    hasParam = true;
                }
            }

            return postData.ToString();
        }
    }
}
